package tech.soulcoder.core.util;

import java.net.InetAddress;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 应用id(5) + 时间戳(毫秒)  + 固定六位机器 +  int类型最大值
 *
 * @author yunfeng.lu
 * @create 2019/2/25.
 */
public class UUIDCreater {

    private static final Logger LOGGER = LoggerFactory.getLogger(UUIDCreater.class);

    private static String appId = "1000";

    static {
        try {
            IP_TAG = formatIp();
        } catch (Exception e) {
            LOGGER.error("ip 标识生成失败", e);
        }
    }

    /**
     * 最大容器容量
     */
    private static final long MAX_ID_CONTAINER_SIZE = 99999L;
    private static final long MIN_ID_CONTAINER_SIZE = 10000L;

    /**
     * 生产者工作状态
     */
    private static AtomicLong AUTO_INCREMENT_ID = new AtomicLong(0);

    /**
     *
     */
    private static String IP_TAG;

    private static String create() {
        synchronized (UUIDCreater.class) {
            if (AUTO_INCREMENT_ID.get() < MAX_ID_CONTAINER_SIZE) {
                AUTO_INCREMENT_ID.set(MIN_ID_CONTAINER_SIZE);
            }
            return String.valueOf(AUTO_INCREMENT_ID.incrementAndGet());
        }
    }

    public static String generate() {

        return appId + getCurrentTimeStampStr() + IP_TAG + create();
    }

    public static String getCurrentTimeStampStr() {
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date(System.currentTimeMillis()));
    }

    /**
     * 取当前机器IP后两节  000001
     *
     * @return
     * @throws Exception
     */
    public static String formatIp() throws Exception {

        byte[] ip_bytes = InetAddress.getLocalHost().getAddress();

        StringBuilder builder = new StringBuilder();

        int data = Math.abs(ip_bytes[2]);

        builder.append(new StringBuilder("000").replace(3 - String.valueOf(data).length(), 3,
            String.valueOf(data)));

        data = Math.abs(ip_bytes[3]);

        builder.append(new StringBuilder("000").replace(3 - String.valueOf(data).length(), 3,
            String.valueOf(data)));

        return builder.toString();

    }

    public static void main(String[] args) throws Exception {

        System.out.println(generate());
        System.out.println(generate().length());

    }

}
